package ru.spbu.math.android.cbrf.dataprovider.handlers;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import ru.spbu.math.android.cbrf.model.Rate;
import ru.spbu.math.android.cbrf.model.StockItem;
import ru.spbu.math.android.cbrf.model.StockItemStore;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Class for parsing data from CBRF and put it in the List of Rate This class extends DefaultHandler
 * @author  Svetlana Zemlyanskaya
 */


//TODO: Remove StockItemStore!
public class CurrencySaxHandler extends DefaultHandler {


    private final String CHAR_CODE = "charCode";
    private final String VALUE = "value";
    private final String VALUTE = "valute";

    private List<Rate> currList;
    /**
	 * @uml.property  name="currency"
	 * @uml.associationEnd  
	 */
    private Rate currency;
    private StringBuilder builder;

    private Date rateDate;
    /**
	 * @uml.property  name="target"
	 * @uml.associationEnd  
	 */
    private StockItem target;

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        builder.append(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        if (this.currency != null) {
            if (localName.equalsIgnoreCase(CHAR_CODE)) {
                String argument = getNameFromString(builder.toString());
                StockItemStore itemStore = StockItemStore.Instance();
                List<StockItem> itemList = itemStore.getItemList();
                boolean wasFound = false;
                StockItem item = new StockItem();
                for (StockItem items : itemList) {
                    if (argument.equals(items.getCode())) {
                        item = items;
                        wasFound = true;
                    }
                }
                if (!wasFound) {
                    item = null;
                }

                currency.setSource(item);
            } else if (localName.equalsIgnoreCase(VALUE)) {
                currency.setValue(getDoubleFromString(builder.toString()));
            } else if (localName.equalsIgnoreCase(VALUTE)) {
                if (currency.getSource() != null) {
                    currList.add(currency);
                }
            }

            builder.setLength(0);
        }
    }

    @Override
    public void startDocument() throws SAXException {
        currList = new ArrayList<Rate>();
        builder = new StringBuilder();
    }

    @Override
    public void startElement(String uri, String localName, String name,
                             Attributes attributes) throws SAXException {
        if (localName.equalsIgnoreCase(VALUTE)) {
            this.currency = new Rate();
            currency.setDate(rateDate);
            currency.setTarget(target);
        }
    }

    /**
	 * Return currency list from XML
	 * @return  List<Currency>
	 * @uml.property  name="currency"
	 */
    public List<Rate> getCurrency() {
        return currList;
    }

    /**
     * Set date for Rate
     *
     * @param date
     */
    public void setDate(Date date) {
        rateDate = date;
    }
    
    /**
	 * Set target for Rate
	 * @param  target
	 * @uml.property  name="target"
	 */
    public void setTarget(StockItem targetItem) {
        target = targetItem;
    }

    //Take double from specified string

    private static double getDoubleFromString(String line) {
        String str = "";
        boolean start = false;
        double result = 0;

        for (int i = 0; i < line.length(); i++) {
            if (Character.isDigit(line.charAt(i))) {
                start = true;
                str += line.charAt(i);
            } else if (line.charAt(i) == '.' || line.charAt(i) == ',') {
                str += '.';
            }
        }
        if (start) {
            result = Double.parseDouble(str);
        } else {
            result = 0;
        }

        return result;

    }

    //Take name from specified string

    private static String getNameFromString(String line) {
        String str = "";
        boolean startName = false, start = false;
        String result = "";
        List<String> resultList = new ArrayList<String>();

        for (int i = 0; i < line.length(); i++) {
            if (Character.isDigit(line.charAt(i)) || Character.isLetter(line.charAt(i))) {
                startName = true;
                start = true;
                str += line.charAt(i);
            } else if (start) {
                start = false;
                resultList.add(str);
                str = "";
            }
        }
        if (start) {
            resultList.add(str);
        }
        if (startName) {
            for (int i = 0; i < resultList.size() - 1; i++) {
                result += resultList.get(i) + " ";
            }
            result += resultList.get(resultList.size() - 1);
        } else {
            result = "";
        }
        return result;
    }
}
